﻿using CommunityToolkit.Mvvm.Input;
using NavigateExample.Services.Navigation;
using NavigateExample.Services.Dialog;
using NavigateExample.Views;

namespace NavigateExample.ViewModels
{
    public partial class HomeViewModel : ViewModelBase, INavigationAware
    {
        private readonly INavigationService navigationService;
        private readonly IDialogService dialogService;
        [ObservableProperty]
        string? userName;
        [ObservableProperty]
        DateTime? loginTime;
        public HomeViewModel(INavigationService navigationService, IDialogService dialogService)
        {
            this.navigationService = navigationService;
            this.dialogService = dialogService;
        }
        [RelayCommand]
        void Logout()
        {
            // 使用新的导航方法（导航到LoginView）
            var parameters = new NavigationParameters();
            parameters.Add("Message", "用户已退出登录");
            navigationService.Navigate<LoginView>(parameters, result =>
            {
                if (result.Success)
                {
                    // 退出成功的处理逻辑
                }
            });
        }
        [RelayCommand]
        void ShowAbout()
        {
            // 示例：使用对话框服务
            var parameters = new DialogParameters();
            parameters.Add("Title", "关于");
            parameters.Add("Message", $"欢迎 {UserName}!");
            parameters.Add("Version", "1.0.0");
            //这个Dialog服务负责打开子窗口
            dialogService.ShowDialog<AboutDialogView>(parameters, result =>
            {
                // 对话框关闭后会执行该回调
                //result里面可以拿到Dialog返回的结果以及子传父的parameter
                
            });
        }

        #region INavigationAware Implementation
        
        public void OnNavigatedTo(NavigationParameters parameters)
        {
            // 当导航到此页面时调用
            
            // 从导航参数中获取用户名和登录时间
            if (parameters.ContainsKey("UserName"))
            {
                UserName = parameters.GetValue<string>("UserName");
            }
            if (parameters.ContainsKey("LoginTime"))
            {
                LoginTime = parameters.GetValue<DateTime>("LoginTime");
            }
        }
        public void OnNavigatedFrom(NavigationParameters parameters)
        {
            // 当从此页面导航离开时调用
        }
        public bool CanNavigateFrom(NavigationParameters parameters)
        {
            // 检查是否可以从此页面导航离开
            return true; // 主页通常可以自由离开
        }
        #endregion
    }
}
